package com.heima.wemedia.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.ChannelDto;
import com.heima.model.wemedia.pojos.WmChannel;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.wemedia.mapper.WmChannelMapper;
import com.heima.wemedia.service.WmChannelService;
import com.heima.wemedia.service.WmNewsService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.nio.channels.Channel;
import java.util.Date;

/**
 * <p>
 * 频道信息表 服务实现类
 * </p>
 *
 * @author itheima
 */
@Slf4j
@Service
public class WmChannelServiceImpl extends ServiceImpl<WmChannelMapper, WmChannel> implements WmChannelService {


    @Autowired
    private WmChannelService wmChannelService;
    @Autowired
    private WmNewsService wmNewsService;

    /*
    * 频道名称模糊分页查询
    * */
    @Override
    public ResponseResult getList(ChannelDto channelDto) {

        //参数校验，确保传入的channelDto对象不是空的
        if (channelDto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //构建分页条件
        Page<WmChannel> page = new Page<>(channelDto.getPage(),channelDto.getSize());

        //构建查询条件
        LambdaQueryWrapper<WmChannel> queryWrapper = new LambdaQueryWrapper<>();
        //按照名称模糊查询
        queryWrapper.like(
                channelDto.getName() != null
                        && StringUtils.isNotBlank(channelDto.getName()),
                WmChannel::getName, channelDto.getName());

        //精确查询：
        //前端没有传Status参数，故作罢
        //Channel channel = new Channel();
        //queryWrapper.eq(channelDto.getStart != null, wmChannel::getStatus, channelDto.getStatus);


        //按照时间倒序排序
        queryWrapper.orderByDesc(WmChannel::getCreatedTime);

        //查询
        page = page(page, queryWrapper);

        //结果校验
        if (page==null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }

        //构建返回
        PageResponseResult pageResponseResult = new PageResponseResult(page);
        pageResponseResult.setCode(AppHttpCodeEnum.SUCCESS.getCode());
        pageResponseResult.setErrorMessage(AppHttpCodeEnum.SUCCESS.getErrorMessage());
        return pageResponseResult;

    }

    @Override
    public ResponseResult saveChannel(WmChannel adChannel) {
        //System.out.println(wmChannel);
        adChannel.setIsDefault(true);
        adChannel.setCreatedTime(new Date());

        LambdaQueryWrapper<WmChannel> queryWrapper = new LambdaQueryWrapper<>();
        LambdaQueryWrapper<WmChannel> eq = queryWrapper.eq(WmChannel::getName, adChannel.getName());


        int count = wmChannelService.count(eq);
        if (count>0) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_EXIST, "频道名已经存在，请换一个频道名");
        }

        this.save(adChannel);

        //wmChannelService.saveBatch()


        return ResponseResult.okResult(this.save(adChannel));
    }

    @Override
    public ResponseResult deleteChannel(Integer id) {
        //校验频道参数：
        if (id==null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }

        //得到该id的频道 并校验频道是否为空
        WmChannel wmChannel = wmChannelService.getById(id);
        if (wmChannel==null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }

        //判断文章是否被禁用，只有状态为被禁用为0的时候才可以被删除
        if (wmChannel.getStatus()) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NO_OPERATOR_AUTH, "文章未被禁用无法被删除");
        }

        //构建查询条件构造器
        LambdaQueryWrapper<WmNews> queryWrapper = new LambdaQueryWrapper<>();

        //判断是否有文章关联
        queryWrapper.eq(WmNews::getChannelId, wmChannel.getId());
        WmNews one = wmNewsService.getOne(queryWrapper);
        if (one != null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NO_OPERATOR_AUTH,"此频道已经被文章引用，无法删除");
        }


        try {
            removeById(id);
        } catch (Exception e) {
            return ResponseResult.errorResult(AppHttpCodeEnum.FILE_STATICURL_ERROR, "删除失败,异常为：" + e);
        }

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    @Override
    public ResponseResult updateChannel(WmChannel wmChannel) {
        //校验参数
        if (wmChannel==null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //判断是否有文章关联该频道，有关联则禁用
        //构建查询条件构造器
        LambdaQueryWrapper<WmNews> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(WmNews::getChannelId, wmChannel.getId());
        WmNews one = wmNewsService.getOne(queryWrapper);
        if (one != null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NO_OPERATOR_AUTH,"此频道已经被文章引用，无法更新");
        }
        //
        //
        //更新
        try {
            updateById(wmChannel);
        } catch (Exception e) {
            ResponseResult.errorResult(AppHttpCodeEnum.FILE_STATICURL_ERROR, "更新失败，异常为：" + e);
        }

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
